/*
* $Id: ApiaryForm.java 276 2011-02-28 22:15:38Z volok-aleksej@yandex.ru $
*
* Copyright 2008-2011 by Volokitin Alexey
* All rights reserved
*
*/
package apiary.ui;

import apiary.common.FormHelper;
import java.util.Hashtable;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.ItemStateListener;

import apiary.Apiary;

public class ApiaryForm extends BackScreen implements ItemEventListener,
                                                      ItemStateListener,
                                                      CommandListener
{
    private CategoryItem curSel;
    private Hashtable types;
    private UIXmlManager uiManager;

    public ApiaryForm(String name, UIXmlManager manager) {
        super(name);
        uiManager = manager;
        types = new Hashtable();
        HashType();
        setCommandListener(this);
        setItemStateListener(this);
    }

    public void addCommand(String type, String name){
        String nameCommand = Apiary.getInstance().getLocaleString(name);
        int typeCommand = ((Integer) types.get(type)).intValue();
        addCommand(new Command(nameCommand, typeCommand, 0));
    }

    public void AddItem(String name, String image, String id) {
        String nameItem = Apiary.getInstance().getLocaleString(name);
        CategoryItem item = FormHelper.createCategoryItem(this, id, nameItem, image);
        append(item);
    }

    public void itemStateChanged(Item item) {
        CategoryItem category = (CategoryItem)item;
        if(category.getActive())
            SetCurSel((CategoryItem)item);
    }

    public void itemNotifyEvent(Item item, String event) {
        if(event.equals(ItemEventListener.PRESS)){
            SetCurSel((CategoryItem)item);
            DisplayItem();
        }
    }

    private void SetCurSel(CategoryItem item) {
        if(item == curSel)
            return;
        curSel = item;
    }

    private void DisplayItem() {
        BackScreen form = uiManager.displayNextForm(curSel.getId());
        form.setBackScreen(this);
    }

    private void HashType() {
        types.put("EXIT", new Integer(Command.EXIT));
        types.put("BACK", new Integer(Command.BACK));
        types.put("SCREEN", new Integer(Command.SCREEN));
    }

    public void commandAction(Command c, Displayable d) {
        Apiary apiary = Apiary.getInstance();
        if(c.getCommandType() == Command.EXIT)
            apiary.exit();
        else if(c.getCommandType() == Command.BACK)
            apiary.Display(backForm);
        else if (c.getCommandType() == Command.SCREEN)
            DisplayItem();
    }
}
